#
#       Author: Alexandros Sigalas
#
#      This program is free software; you can redistribute it and/or modify
#      it under the terms of the GNU General Public License as published by
#      the Free Software Foundation; either version 2 of the License, or
#      (at your option) any later version.
#      
#      This program is distributed in the hope that it will be useful,
#      but WITHOUT ANY WARRANTY; without even the implied warranty of
#      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#      GNU General Public License for more details.
#      
#      You should have received a copy of the GNU General Public License
#      along with this program; if not, write to the Free Software
#      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#      MA 02110-1301, USA.

import dxfcolors
import sdxf
from mesh2vec.material import indexColorFromRGB

def _col2DXF(color):
    return indexColorFromRGB(color, dxfcolors.color_map)

def poly(pl, flatten=False, layer=None, color=None):
    #TODO: mesh2vec.dxf.export.poly()
    tmp= pl.copy()
    if flatten:
        tmp= pl.flattenZ()
        
    entities= list()
    polys= list()
    org_point= [0.0,0.0,0.0]
            
    if layer is None:
        layer= '0'
    
    if color is None:
        color= _col2DXF(pl.material.fill_color)

    polys.append(tmp)
    polys.extend([pl for pl in tmp.holes])
    for pl in polys:
        points= [v.co for v in pl]
        if points:
            dxf_poly= sdxf.PolyLine(points, org_point, closed=1, layer=layer, color=color)
            entities.append(dxf_poly)
            
    return entities

def drawing(dwg, filename):

        dxf = sdxf.Drawing()
        dxf.styles.append(sdxf.Style())         #table styles
        dxf.views.append(sdxf.View('Normal'))     #table view
        dxf.views.append(sdxf.ViewByWindow('Window',leftBottom=(1,0),rightTop=(2,1)))  #idem
    
        for layer_name, layer in self.layers:
            if self.layerMode == "byMaterial":
                mat = self.materials[layer_name]
                l_color = col2DXF(mat.fill_color)
                if l_color == 0:
                    l_color = 255
                pl_color = 256
                l_name = layername.replace(".","_")
            else:
                l_name = "0"
                l_color = 255
                pl_color = None
            dxf.layers.append(DXF.Layer(color=l_color, name=l_name))

            for pl in layer:
                tmp = pl.copy()
                tmp.scale(self.scale)
                tmp.flatten()
                dxf.extend(tmp.drawDXF(layer=l_name, color=pl_color))

        dxf.saveas(filename)
